package com.example.dbutils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectionFactory {
	public static String className;
	public static String url;
	public static String userName;
	public static String password;
	public static String dataSource;

	private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

	/**
	 * 获取数据库连接
	 * */
	public static Connection getConnection() {
		Connection conn = threadLocal.get();
		try {
			if (conn == null || conn.isClosed()) {
				if (!DriverManager.getDrivers().hasMoreElements())
					Class.forName(className);
				conn = DriverManager.getConnection(url, userName, password);
				threadLocal.set(conn);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 获取数据库连接
	 * */
	public static Connection getConnection(String className, String url,
			String userName, String password) {
		Connection conn = null;
		try {
			Class.forName(className);
			conn = DriverManager.getConnection(url, userName, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 从数据源中获取连接
	 * */
	public static Connection getConnectionFromInitialContext() {
		Connection conn = null;
		try {
			InitialContext ic = new InitialContext();
			DataSource ds = (DataSource) ic.lookup(dataSource);
			conn = ds.getConnection();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
}
